package com.yunsc.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.media.entity.YunscUploadFileEntity;
import com.yunsc.media.service.YunscUploadFileService;
import com.yunsc.store.dao.YunscH5SettingDao;
import com.yunsc.store.dao.YunscStoreDao;
import com.yunsc.store.dao.YunscWxappSettingDao;
import com.yunsc.store.entity.YunscH5SettingEntity;
import com.yunsc.store.entity.YunscStoreEntity;
import com.yunsc.store.entity.YunscUserEntity;
import com.yunsc.store.entity.YunscWxappSettingEntity;
import com.yunsc.store.service.YunscStoreService;
import com.yunsc.store.service.YunscStoreSettingService;
import com.yunsc.store.service.YunscUserService;
import com.yunsc.store.vo.StoreDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("yunscStoreService")
public class YunscStoreServiceImpl extends ServiceImpl<YunscStoreDao, YunscStoreEntity> implements YunscStoreService {


    @Resource
    private YunscUploadFileService uploadFileService;
    @Resource
    private YunscStoreSettingService storeSettingService;
    @Resource
    private YunscWxappSettingDao wxappSettingDao;
    @Resource
    private YunscH5SettingDao h5SettingDao;
    @Resource
    private YunscUserService userService;



    @Override
    public YunscStoreEntity queryStoreInfo(Integer storeId) {
        YunscStoreEntity storeEntity = this.getById(storeId);
        YunscUploadFileEntity logoImage = uploadFileService.queryFileById(storeEntity.getLogoImageId());
        storeEntity.setLogoImage(logoImage);
        return storeEntity;
    }

    @Override
    public StoreDataVO queryStoreData(Integer storeId) {
        // 1、实时交易概况
        // 获取订单概览数据

        // 新增会员数

        // 2、统计数据
        // 订单概况
        // 商品总数量
        // 3、待发货订单(笔)
        // 已售罄商品
        // 4、获取近七日交易走势

        return null;
    }

    @Override
    @Transactional
    public void updateStoreInfo(YunscStoreEntity storeInfo, Integer storeId) {
        YunscStoreEntity storeEntity = this.getById(storeId);
        if (storeEntity == null) {
            log.error("storeId:{}不存在", storeId);
            return;
        }
        BeanUtils.copyProperties(storeInfo, storeEntity);
        storeEntity.setStoreId(storeId);
        this.updateById(storeEntity);

    }

    @Override
    public Map<String, Object> queryStoreDataByPlatform(String platform, Integer storeId) {
        YunscStoreEntity storeInfo = this.queryStoreInfo(storeId);
        Map<String, Object> settingAll = storeSettingService.queryStoreSettingAll(storeId);
        Object app_theme = settingAll.get("app_theme"); // 主题
        Object setting = JSON.parseObject(app_theme.toString(), Map.class).get("data");
        String client = null;
        Map<String, Object> clientData = new HashMap<>();
        if ("H5".equals(platform)){
            YunscH5SettingEntity settingEntity = h5SettingDao.selectOne(new QueryWrapper<YunscH5SettingEntity>()
                    .eq("`key`", "basic").eq("store_id", storeId));
            Map<String, Object> h5Setting = new HashMap<>();
            h5Setting.put("setting", JSON.parseObject(settingEntity.getValues()));
            clientData.put("h5", h5Setting);
            client = "h5";
        }else if ("WXAPP".equals(platform)){
            YunscWxappSettingEntity settingEntity = wxappSettingDao.selectOne(
                    new QueryWrapper<YunscWxappSettingEntity>().eq("`key`", "basic").eq("store_id", storeId));
            Map<String, Object> h5Setting = new HashMap<>();
            h5Setting.put("setting", JSON.parseObject(settingEntity.getValues()));
            clientData.put("WXAPP", h5Setting);
            client = "WXAPP";
        }else{
            log.error("平台:{}不存在", platform);
            return null;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("storeInfo", storeInfo);
        data.put("setting", setting);
        data.put("clientData", clientData);
        data.put("client", client);
        return data;
    }

    @Override
    public Map<String, Object> queryNewUserByday(Integer storeId) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 当天开始时间（0点0分0秒）
        LocalDateTime startOfDay = today.atStartOfDay();
        long startSeconds = startOfDay.toEpochSecond(ZoneOffset.UTC);
        // 当天结束时间（23点59分59秒）
        LocalDateTime endOfDay = today.atTime(23, 59, 59);
        long endSeconds = endOfDay.toEpochSecond(ZoneOffset.UTC);

        // 查询用户数量
        long tda = this.getUserList(startSeconds, endSeconds, storeId);
        long yda = this.queryNewUserByYesterday(storeId);
        Map<String, Object> map = new HashMap<>();
        map.put("ytd", String.valueOf(yda));
        map.put("tday", String.valueOf(tda));
        return map;
    }

    @Override
    public String queryUserTotal(Integer storeId) {
        return String.valueOf(userService.count(new LambdaQueryWrapper<YunscUserEntity>()
                .eq(YunscUserEntity::getStoreId, storeId)
                .eq(YunscUserEntity::getIsDelete, 0)));
    }
    public long queryNewUserByYesterday(Integer storeId) {
        // 获取当前日期前一天的日期
        LocalDate yesterday = LocalDate.now().minus(1, ChronoUnit.DAYS);
        // 计算昨天开始时间（0点0分0秒）的时间戳
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        long yesterdayStartInSeconds = startOfYesterday.toEpochSecond(ZoneOffset.UTC);
        // 计算昨天结束时间（23点59分59秒）的时间戳
        LocalDateTime endOfYesterday = yesterday.plusDays(1).atStartOfDay().minusSeconds(1);
        long yesterdayEndInSeconds = endOfYesterday.toEpochSecond(ZoneOffset.UTC);

        return getUserList(yesterdayStartInSeconds, yesterdayEndInSeconds, storeId);
    }

    public long getUserList(long startSeconds, long endSeconds, Integer storeId) {
        LambdaQueryWrapper<YunscUserEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscUserEntity::getStoreId, storeId);
        lqw.between(YunscUserEntity::getCreateTime, startSeconds, endSeconds);
        return userService.count(lqw);
    }



}